import React, {useEffect, useState} from 'react';
import style from './AddPersonalCircle.module.scss'
import '@wangeditor/editor/dist/css/style.css'
import {Editor, Toolbar} from "@wangeditor/editor-for-react";
import {Button, message} from "antd";
import {
    addPersonalCircle,
    addPersonalCircleVideo,
    inquirePersonalCircleList,
    updatePersonalCircle
} from "./AddPersonalCircleApi";
import {addPersonalCircleImg} from "./AddPersonalCircleApi";
import {useNavigate, useLocation} from "react-router-dom";

function AddPersonalCircle() {
    const [editor, setEditor] = useState(null)
    const [html, setHtml] = useState('<p>请输入内容</p>')
    const Navigate = useNavigate()
    const Location = useLocation()
    // 工具栏配置
    const toolbarConfig = {}

    // 编辑器配置
    const editorConfig = {
        placeholder: '请输入内容...',
        MENU_CONF: {
            //图片上传
            uploadImage: {
                // 自定义博客图片上传
                async customUpload(file, insertFn) {
                    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                    if (!isJpgOrPng) {
                        message.warning('你只能上传JPG/PNG文件!');
                        return false
                    }
                    const isLt2M = file.size / 1024 / 1024 < 2;

                    if (!isLt2M) {
                        message.warning('图片大小不能超过 2MB!');
                        return false
                    }

                    const formData = new FormData()
                    formData.append('file', file)
                    addPersonalCircleImg(formData).then(res => {
                        const imgUrl = process.env.REACT_APP_URL + res.data.url
                        insertFn(imgUrl)
                    })
                },
            },

            uploadVideo: {
                async customUpload(file, insertFn) {
                    const type = ['video/mp4', 'video/mp3']
                    const isJpgOrPng = type.includes(file.type);
                    if (!isJpgOrPng) {
                        message.error('你只能上传mp3/mp4文件!');
                        return false
                    }
                    const isLt2M = file.size / 1024 / 1024 < 10;
                    if (!isLt2M) {
                        message.error('单个视频大小不能超过 10MB!');
                        return false
                    }
                    const formData = new FormData()
                    formData.append('file', file)
                    addPersonalCircleVideo(formData).then(res => {
                        const imgUrl = process.env.REACT_APP_URL + res.data.url
                        insertFn(imgUrl)
                    }).catch(e => {
                        console.log(e)
                    })
                }
            }
        }
    }
    // 提交
    const save = () => {
        if (Location.search) {
            const id = Number(Location.search.split('=')[1])
            updatePersonalCircle({id, text: html}).then(res => {
                if (res.code === '200') {
                    message.success('发布成功')
                    setHtml('<p>请输入内容</p>')
                    Navigate('/HomeSystem/PersonalCircleList')
                } else {
                    message.error('提交失败')
                }
            }).catch(e => {
                message.error('提交失败')
            })
            return
        } else {
            addPersonalCircle({text: html}).then(res => {
                if (res.code === '200') {
                    message.success('发布成功')
                    setHtml('<p>请输入内容</p>')
                    Navigate('/HomeSystem/PersonalCircleList')
                } else {
                    message.error('提交失败')
                }
            }).catch(e => {
                message.error('提交失败')
            })
        }
    }
    // 及时销毁 editor ，重要！
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor])

    // 获取数据
    useEffect(() => {
        if (Location.search) {
            const id = Number(Location.search.split('=')[1])
            inquirePersonalCircleList({ListQuery: null, SearchData: {id}}).then(res => {
                if (res.code === '200') {
                    setHtml(res.data.rows[0].circleContent)
                } else {
                    message.error('查询失败')
                }
            }).catch(e => {
                message.error('查询失败')
            })
        }
    }, [Location.search])

    return (
        <div className={style.AddPersonalCircle}>
            <div className={style.redactArea}>
                <div style={{zIndex: 100}}>
                    <Toolbar
                        editor={editor}
                        defaultConfig={toolbarConfig}
                        mode="default"
                        style={{borderBottom: '1px solid #ccc'}}
                    />
                    <Editor
                        defaultConfig={editorConfig}
                        value={html}
                        onCreated={setEditor}
                        onChange={editor => setHtml(editor.getHtml())}
                        mode="default"
                        style={{height: '100%'}}
                    />
                </div>
                <div className={style.save}>
                    <Button type="primary" onClick={save}>提交</Button>
                </div>
            </div>
        </div>
    );
}

export default AddPersonalCircle;
